﻿using AutoMapper;
using BasicInformation.ApiWrite.Application.Command.Inbound;
using BasicInformation.Domain;
using BasicInformation.ErrorCode;
using BasicInformation.Infrastructure.Implement;
using MediatR;
using System.Text;

namespace BasicInformation.ApiWrite.Application.Handler.Inbound
{
    public class AddInboundHandler : IRequestHandler<AddInboundCommand, ApiResult<int>>
    {
        private readonly DatabaseContext db;
        private readonly ILogger<AddInboundHandler> logger;
        private readonly IMapper mapper;

        public AddInboundHandler(DatabaseContext db,ILogger<AddInboundHandler> logger,IMapper mapper)
        {
            this.db = db;
            this.logger = logger;
            this.mapper = mapper;
        }
        public async Task<ApiResult<int>> Handle(AddInboundCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            var inbound = mapper.Map<InboundModel>(request);
            int r = await db.SqlSugar.Insertable(inbound).ExecuteCommandAsync();
            if (r > 0)
            {
                result.Msg = "库存盘点入库添加成功";
                result.Data = r;
                result.Code = ApiEnum.OK;
                logger.LogInformation(result.Msg);
            }
            else
            {
                result.Msg = "库存盘点入库添加失败";
                result.Data = r;
                result.Code = ApiEnum.Fail;
                logger.LogError(result.Msg);
            }
            return await Task.FromResult(result);

        }
    }
}
